package com.cx.mall.user.controller;


import com.cx.mall.common.utils.JwtUtils;
import com.cx.mall.common.utils.ResponseVO;
import com.cx.mall.common.model.user.Login;
import com.cx.mall.common.model.user.UserInfo;
import com.cx.mall.user.service.ILoginService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired // 注入业务层
    private ILoginService loginService;

//    @PostMapping("/login")
//    public ResponseVO login(@RequestBody Login userLogin){
//        UserInfo login = loginService.login(userLogin.getUsername(),userLogin.getPassword());
//        return ResponseVO.success(login);
//    }
    @PostMapping("/login")
    public ResponseVO<UserInfo> login(@RequestBody Login userLogin, HttpServletResponse response) throws Exception {
        // 登录
        UserInfo userInfo = loginService.login(userLogin.getUsername(), userLogin.getPassword());
        // 登录成功后创建token，并保存用户信息
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        String token = JwtUtils.generateToken(map);
        // 将token写入响应头
        response.setHeader("Authorization", token);
        return ResponseVO.success(userInfo);
    }
}

